package com.lc.hongtai.activity;

import android.app.DatePickerDialog;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.lc.hongtai.MyApplication;
import com.lc.hongtai.R;
import com.lc.hongtai.adapter.InvestManageDetail01Adapter;
import com.lc.hongtai.adapter.InvestManageDetail02Adapter;
import com.lc.hongtai.adapter.InvestManageDetail03Adapter;
import com.lc.hongtai.adapter.InvestManageDetailAdapter;
import com.lc.hongtai.conn.JsonAccessToken;
import com.lc.hongtai.conn.JsonTendout;
import com.lc.hongtai.dialogs.DateTimePickDialog;
import com.lc.hongtai.toast.LovelyToast;
import com.lc.hongtai.view.SimpleDividerItemDecoration;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;


public class InvestManageDetailActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvtitle;
    private TextView tv01;
    private ImageView iv01;
    private Spinner sp01;
    private RecyclerView rv01;
    private List<String> stringList = new ArrayList<>();
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<JsonTendout.Info.ListContent> list = new ArrayList<>();
    private PtrFrameLayout store_house_ptr_frame;
    private PtrClassicDefaultHeader header;
    private ImageView ivback;
    private TextView tvtitleright;
    private String show_type = "tending";

    public int nowPage = 1;
    public int totalPages = 1;
    public int pageSize = 0;
    public int totalRows = 0;
    private boolean canLoadMore = true;
    private TextView tv04;

    private ImageView iv03;
    private ImageView iv02;

    private LinearLayout ll02;
    private TextView tv03;
    private LinearLayout ll03;


    private TextView et02;




    private DatePickerDialog pickerDialog;
    private TextView curEditView;
    private DatePickerDialog.OnDateSetListener mDateSetListener;
    public String st, et;








    private PopupWindow popLeft;
    private View layoutLeft;
    private ListView menulistLeft;

    private LinearLayout pop_layout;


    private LinearLayout invest_title_ll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invest_manage_detail);

        initView();
        initListener();
        initRefreshListener();
        show_type = "tending";
        iv02.setVisibility(View.GONE);
        iv03.setVisibility(View.GONE);

        ll02.setVisibility(View.GONE);
        ll03.setVisibility(View.GONE);

        tvtitle.setText("成功转让债权");
        mAdapter = new InvestManageDetailAdapter(this, list);
        rv01.setAdapter(mAdapter);
        getAccessToken(true, nowPage);
    }

    private void initListener() {
        mDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                curEditView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);

                list.clear();
                mAdapter.notifyDataSetChanged();

            }
        };
        iv01.setOnClickListener(this);
        tv01.setOnClickListener(this);

        et02.setOnClickListener(this);

         
    }

    private void initView() {
        this.store_house_ptr_frame = (PtrFrameLayout) findViewById(R.id.store_house_ptr_frame);
        this.rv01 = (RecyclerView) findViewById(R.id.rv_01);


        this.et02 = (TextView) findViewById(R.id.et_02);

        this.ll03 = (LinearLayout) findViewById(R.id.ll_03);
        this.tv03 = (TextView) findViewById(R.id.tv_03);
        this.ll02 = (LinearLayout) findViewById(R.id.ll_02);

        this.iv02 = (ImageView) findViewById(R.id.iv_02);
        this.iv03 = (ImageView) findViewById(R.id.iv_03);

        this.tv04 = (TextView) findViewById(R.id.tv_04);
        this.sp01 = (Spinner) findViewById(R.id.sp_01);
        this.iv01 = (ImageView) findViewById(R.id.iv_01);
        this.tv01 = (TextView) findViewById(R.id.tv_01);
        this.ivback = (ImageView) findViewById(R.id.iv_back);
        this.tvtitle = (TextView) findViewById(R.id.tv_title);

        this.pop_layout = (LinearLayout) findViewById(R.id.pop_layout);



        this.invest_title_ll = (LinearLayout) findViewById(R.id.invest_title_ll);
        invest_title_ll.setOnClickListener(this);


        stringList.clear();
        stringList.add("竞标中的投资");
        stringList.add("逾期的投资");
        stringList.add("已回收的投资");
        stringList.add("回收中的投资");
//        stringList.add("已回收的投资");
        //stringList.add("逾期的投资");

        sp01.setSelection(getIntent().getIntExtra("id", 0));
        header = new PtrClassicDefaultHeader(this);
        store_house_ptr_frame.setHeaderView(header);
        mLayoutManager = new LinearLayoutManager(this);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.line_divider3);
        rv01.addItemDecoration(new SimpleDividerItemDecoration(this, drawable, 30));

        rv01.setLayoutManager(mLayoutManager);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_01:
            case R.id.invest_title_ll:
            case R.id.iv_01:
                //sp01.performClick();
                getPopLayout();


                break;







        }
    }



    private void getAccessToken(final boolean isShow, final int page) {
        new JsonAccessToken("user/tendout", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initData(info.access_token, isShow, page);
                    } else {
                        //  UtilToast.show(InvestManageDetailActivity.this, "安全验证失败！");
                        LovelyToast.makeText(InvestManageDetailActivity.this, "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        canLoadMore = true;
                        if (!isShow) {
                            store_house_ptr_frame.refreshComplete();
                        }
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //   UtilToast.show(InvestManageDetailActivity.this, "安全验证失败！");
                LovelyToast.makeText(InvestManageDetailActivity.this, "安全验证失败！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                canLoadMore = true;
                if (!isShow) {
                    store_house_ptr_frame.refreshComplete();
                }
            }
        }).execute(this, isShow);

    }

    private void initData(String access_token, final boolean isShow, final int page) {

        new JsonTendout(access_token, String.valueOf(page), MyApplication.myPreferences.readUid(), show_type, "20141414", "20170617",


                new AsyCallBack<JsonTendout.Info>() {

                    @Override
                    public void onStart(int type) throws Exception {
                        super.onStart(type);
                    }

                    @Override
                    public void onSuccess(String toast, int type, JsonTendout.Info info) throws Exception {
                        if (info != null) {
                            list.clear();
                            list.addAll(info.list);
                            tv04.setText("￥" + info.total_money + "元");


                            tv03.setText("￥" + info.total_money);

                            nowPage = info.page.nowPage;
                            totalPages = info.page.totalPages;
                            pageSize = info.page.pageSize;
                            totalRows = info.page.totalRows;
                            if (list.isEmpty()) {
                                // ToastUtils.show(InvestManageDetailActivity.this, "无记录！");
                                LovelyToast.makeText(InvestManageDetailActivity.this, "无记录！", 0, LovelyToast
                                        .SUCCESS, LovelyToast.SCALE);
                            }
                        }
                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                        //   UtilToast.show(InvestManageDetailActivity.this, JsonTendout.TOAST);
                        LovelyToast.makeText(InvestManageDetailActivity.this, JsonTendout.TOAST, 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        store_house_ptr_frame.refreshComplete();
                    }

                    @Override
                    public void onEnd(String toast, int type) throws Exception {
                        if (!isShow) {
                            store_house_ptr_frame.refreshComplete();
                        }
                        canLoadMore = true;
                        mAdapter.notifyDataSetChanged();
                    }

                }).execute(InvestManageDetailActivity.this, isShow);
    }

    private void initRefreshListener() {
        rv01.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                if (dy > 0 && canLoadMore && lastVisibleItemPosition + 1 == mAdapter.getItemCount()) {
                    canLoadMore = false;
                    if (nowPage < totalPages) {
                        getAccessToken(true, nowPage + 1);
                    } else {
                        //UtilToast.show(InvestManageDetailActivity.this, "当前页已是最后一页");
                    }
                }
            }
        });

        store_house_ptr_frame.setPtrHandler(new PtrHandler() {


            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibleItemPosition();
                return firstVisibleItemPosition == 0 || list.size() == 0;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                list.clear();
                nowPage = 1;
                getAccessToken(false, nowPage);
            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }


    /*  private void creatDataDialog() {
          if (TextUtils.isEmpty(curEditView.getText().toString())) {
              pickerDialog = new DatePickerDialog(this, mDateSetListener, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
          } else {
              String[] data = curEditView.getText().toString().split("-");
              pickerDialog = new DatePickerDialog(this, mDateSetListener, Integer.parseInt(data[0]), (Integer.parseInt(data[1]) - 1), Integer.parseInt(data[2]));
          }
          pickerDialog.show();
      }*/
    private void creatDataDialog(TextView textView) {

        DateTimePickDialog dateTimePickDialog = new DateTimePickDialog(this, null);

        dateTimePickDialog.dateTimePicKDialog(textView);

    }

    public void getPopLayout() {

        if (popLeft != null && popLeft.isShowing()) {
            popLeft.dismiss();
        } else {
        /*    layoutLeft = LayoutInflater.inflate(
                    R.layout.pop_menulist, null);*/
     /*       layoutLeft = LayoutInflater.from(context).inflate(R.layout.pop_menulist, null);
            menulistLeft = (ListView) layoutLeft
                    .findViewById(R.id.menulist);
            menulistLeft.setAdapter(new ArrayAdapter<String>(InvestManageDetailActivity.this, R.layout.spinner_item_01, stringList));
*/
            layoutLeft = LayoutInflater.from(context).inflate(R.layout.pop_menulist1, null);
            menulistLeft = (ListView) layoutLeft
                    .findViewById(R.id.menulist);
            menulistLeft.setAdapter(new ArrayAdapter<String>(InvestManageDetailActivity.this, R.layout.pop_list_item, stringList));

            menulistLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                    tv01.setText(stringList.get(position));
                    if (!list.isEmpty()) {
                        list.clear();
                    }

                    nowPage = 1;
                    switch (position) {
                        case 0:
                            //竞标中
                            show_type = "tending";
                            iv02.setVisibility(View.GONE);
                            iv03.setVisibility(View.GONE);

                            ll02.setVisibility(View.GONE);
                            ll03.setVisibility(View.GONE);

                            tvtitle.setText("竞标中的投资");

                            mAdapter = new InvestManageDetailAdapter(InvestManageDetailActivity.this, list);
                            rv01.setAdapter(mAdapter);

                            getAccessToken(true, nowPage);
                            break;
                        case 1:

                            //逾期

                            ll02.setVisibility(View.GONE);
                            ll03.setVisibility(View.GONE);

                            show_type = "tendbreak";
                            tvtitle.setText("逾期中的投资");
                            mAdapter = new InvestManageDetail01Adapter(InvestManageDetailActivity.this, list);
                            rv01.setAdapter(mAdapter);
                            getAccessToken(true, nowPage);
                            break;

                        case 2:

                            //已回收
                            show_type = "tenddone";
                            iv02.setVisibility(View.GONE);
                            iv03.setVisibility(View.INVISIBLE);

                            ll02.setVisibility(View.GONE);
                            ll03.setVisibility(View.GONE);

                            tvtitle.setText("已回收中的投资");
                            mAdapter = new InvestManageDetail02Adapter(InvestManageDetailActivity.this, list);
                            rv01.setAdapter(mAdapter);
                            getAccessToken(true, nowPage);
                            break;
                        case 3:



//回收中
                            iv02.setVisibility(View.GONE);
                            iv03.setVisibility(View.GONE);

                            ll02.setVisibility(View.GONE);
                            ll03.setVisibility(View.GONE);

                            show_type = "tendbacking";
                            tvtitle.setText("回收中的投资");

                            mAdapter = new InvestManageDetail03Adapter(InvestManageDetailActivity.this, list);
                            List<String> mDatas;
                            mDatas = new ArrayList<String>();
                            for (int i = 'A'; i < 'z'; i++) {
                                mDatas.add("" + (char) i);
                            }
                            //   mAdapter=new BorrowingTestAdapter(InvestManageDetailActivity.this,mDatas);

                            rv01.setAdapter(mAdapter);
                            getAccessToken(true, nowPage);
                            break;
                    }


                    popLeft.dismiss();
                }
            });
            popLeft = new PopupWindow(layoutLeft, pop_layout.getWidth(),
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.colorWhite));
            popLeft.setBackgroundDrawable(cd);
            popLeft.setAnimationStyle(R.style.PopupAnimation);
            popLeft.update();
            popLeft.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            popLeft.setTouchable(true); // 设置popupwindow可点击
            popLeft.setOutsideTouchable(true); // 设置popupwindow外部可点击
            popLeft.setFocusable(true); // 获取焦点

            popLeft.showAsDropDown(tv01, 0, 0);
            popLeft.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 如果点击了popupwindow的外部，popupwindow也会消失
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        popLeft.dismiss();
                        return true;
                    }
                    return false;
                }
            });

        }


    }
}
